package com.zzsoft.nettysocket;/**
 * Created by zhanghb on 2019/9/2.
 */

import com.zzsoft.util.SocketUtil;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.SocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description
 * @Author Zhanghb
 * @Date
 */
@Slf4j
public class ServerHandler extends ChannelHandlerAdapter
{
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("连接激活");
        log.info("实例名称："+ctx.name());
        String channelId =ctx.channel().id().asLongText();
        log.info("channelId："+channelId);
        if(SocketUtil.get(channelId)==null){
            //将channel通过channelId放入缓存中
            SocketUtil.add(channelId,ctx.channel());
            log.info("缓存channel,key:"+channelId);
        }else{
            //todo 对channelId进行对比，及业务处理
        }
        // 若没有StringEncoder，则发送不出去字符串。
        ctx.writeAndFlush("hello,world! 你好,世界!");
       log.info("写入完成");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("实例名称2："+ctx.name());
        log.info("从客户端读取数据："+msg);
        String channelId =ctx.channel().id().asLongText();
        log.info("channelId2："+channelId);
        if(SocketUtil.get(channelId)!=null){
            log.info("已缓存，可以进行业务操作");
        }else{
            log.info("未缓存，可以进行业务操作");
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.warn( "发生错误，关闭链接。", cause);
        SocketUtil.remove(ctx.channel());
        ctx.close();
    }

    /**
     * 连接断开时调用
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        log.warn( "连接关闭。");
        SocketUtil.remove(ctx.channel());
        ctx.close();
    }
}

